<template>
  <MyDrawer ref="myRef" title="状态详情" @submit="submit" :disabled="false">
    <el-form :model="drawerProps.row" :rules="rules" label-width="100" ref="formRef">
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="drawerProps.row.name"></el-input>
      </el-form-item>
      <el-form-item label="字体颜色" prop="textColor">
        <el-color-picker v-model="drawerProps.row.textColor" popper-class="hex" size="large"></el-color-picker>
      </el-form-item>
      <el-form-item label="小图标">
        <ChooseFile v-model:url="drawerProps.row.cover" file-type="image"></ChooseFile>
      </el-form-item>
      <el-form-item label="预览" v-if="drawerProps.row.cover">
        <div class="flex">
          <div class="flex flex-col justify-center mr-5px">
            <el-image :src="url(prefix, drawerProps.row.cover)" class="w-20px rounded-5px"></el-image>
          </div>
          <div>
            <span :style="{ color: drawerProps.row.textColor }">{{ drawerProps.row.name }}</span>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <SuCaiPopup ref="suRef" :maxSelect="1" fileType="image" @confirm="getUrl"></SuCaiPopup>
  </MyDrawer>
</template>

<script setup lang="ts">
import MyDrawer from "@/components/MyDrawer/index.vue";
import { ref } from "vue";
import { validHex } from "@/utils/eleValidate";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import ChooseFile from "@/components/ChooseFile/index.vue";
import { useUserStore } from "@/stores/modules/user";
import { url } from "@/utils/index";

const {
  userInfo: { prefix }
} = useUserStore();

const rules: FormRules = {
  name: [{ max: 20, min: 1, message: "字符在1-20个字符之间", required: true }],
  textColor: [{ required: true, validator: validHex }]
};

interface DrawerProps {
  row: any;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
}

const initData: any = {
  name: "",
  cover: "",
  textColor: "#000"
};

const drawerProps = ref<DrawerProps>({
  row: JSON.parse(JSON.stringify(initData))
});

const getUrl = (val: any) => {
  drawerProps.value.row.cover = val[0].origin_name;
};

const myRef = ref<InstanceType<typeof MyDrawer> | null>();

const acceptParams = (params: any) => {
  drawerProps.value = params;
  myRef.value?.acceptParams();
};

const formRef = ref<FormInstance>();

const submit = () => {
  if (!formRef.value) return;
  formRef.value?.validate(async valid => {
    if (valid) {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success("成功");
      await drawerProps.value.getTable!();
      myRef.value?.close();
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style></style>
